#include "camerawidget.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QCameraInfo>

CameraWidget::CameraWidget(QWidget *parent) : QWidget(parent), m_isRecording(false)
{
    // 初始化UI组件
    m_viewfinder = new QCameraViewfinder(this);
    m_captureButton = new QPushButton("拍照", this);
    m_captureButton->setMinimumHeight(40);
    m_recordButton = new QPushButton("录制", this);
    m_recordButton->setMinimumHeight(40);
    m_statusLabel = new QLabel("准备就绪", this);
    m_statusLabel->setMinimumHeight(30);
    this->setStyleSheet(R"(
    QPushButton{
        background-color:#0099ff;
        border: 1px solid #0099ff;
        border-radius: 8px;
    }QLabel{
        background-color:#ffffff;
        border: 1px solid #ffffff;
        border-radius: 4px;
    }
   
    )");
    // 布局设置
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    QHBoxLayout *buttonLayout = new QHBoxLayout;
    
    buttonLayout->addWidget(m_captureButton);
    buttonLayout->addWidget(m_recordButton);
    mainLayout->addWidget(m_statusLabel);
    mainLayout->addWidget(m_viewfinder);
    mainLayout->addLayout(buttonLayout);
    
    // 获取默认摄像头设备
    m_camera = new QCamera(QCameraInfo::defaultCamera(), this);
    
    // 设置取景器
    m_camera->setViewfinder(m_viewfinder);
    
    // 初始化图像捕获
    m_imageCapture = new QCameraImageCapture(m_camera, this);
    
    // 初始化视频录制
    m_mediaRecorder = new QMediaRecorder(m_camera, this);
    
    // 连接信号和槽
    connect(m_captureButton, &QPushButton::clicked, this, &CameraWidget::onCaptureButtonClicked);
    connect(m_recordButton, &QPushButton::clicked, this, &CameraWidget::onRecordButtonClicked);
    connect(m_imageCapture, &QCameraImageCapture::imageCaptured, this, &CameraWidget::onImageCaptured);
    connect(m_camera, SIGNAL(error(QCamera::Error)), this, SLOT(onError(QCamera::Error)));
    
    // 启动摄像头
    m_camera->start();
    updateStatus("摄像头已启动");
}

CameraWidget::~CameraWidget()
{
    if (m_camera->status() == QCamera::ActiveStatus)
        m_camera->stop();
}

void CameraWidget::onCaptureButtonClicked()
{
    if (m_camera->status() == QCamera::ActiveStatus) {
        updateStatus("正在拍照...");
        // 捕获图像（异步操作）
        m_imageCapture->capture();
    } else {
        updateStatus("摄像头未启动");
    }
}

void CameraWidget::onRecordButtonClicked()
{
    if (m_isRecording) {
        // 停止录制
        m_mediaRecorder->stop();
        m_recordButton->setText("录制");
        m_isRecording = false;
        updateStatus("录制已停止");
    } else {
        // 开始录制
        QString fileName = QFileDialog::getSaveFileName(this, "保存视频", 
                                                        QDir::homePath(), "视频文件 (*.mp4)");
        if (!fileName.isEmpty()) {
            m_mediaRecorder->setOutputLocation(QUrl::fromLocalFile(fileName));
            m_camera->setCaptureMode(QCamera::CaptureVideo);
            m_mediaRecorder->record();
            m_recordButton->setText("停止");
            m_isRecording = true;
            updateStatus("正在录制...");
        }
    }
}

void CameraWidget::onImageCaptured(int id, const QImage &preview)
{
    Q_UNUSED(id);
    
    // 保存图像
    QString fileName = QFileDialog::getSaveFileName(this, "保存图片", 
                                                    QDir::homePath(), "图像文件 (*.jpg)");
    if (!fileName.isEmpty()) {
        if (preview.save(fileName, "JPG")) {
            updateStatus("图片已保存: " + fileName);
        } else {
            updateStatus("保存图片失败");
        }
    } else {
        updateStatus("取消保存图片");
    }
}

void CameraWidget::updateStatus(const QString &status)
{
    m_statusLabel->setText(status);
    qDebug() << "Camera Status:" << status;
}

void CameraWidget::onError(QCamera::Error error)
{
    QString errorMsg;
    switch (error) {
    case QCamera::NoError:
        return;
    case QCamera::CameraError:
        errorMsg = "摄像头错误";
        break;
    case QCamera::InvalidRequestError:
        errorMsg = "无效请求";
        break;
    case QCamera::ServiceMissingError:
        errorMsg = "摄像头服务缺失，请检查系统驱动";
        break;
    case QCamera::NotSupportedFeatureError:
        errorMsg = "不支持的功能";
        break;
    default:
        errorMsg = "未知错误";
        break;
    }
    
    QMessageBox::critical(this, "摄像头错误", errorMsg);
    updateStatus(errorMsg);
}
